package com.cn.lp.ai.factory;

import org.springframework.ai.autoconfigure.qianfan.QianFanChatProperties;
import org.springframework.ai.autoconfigure.qianfan.QianFanConnectionProperties;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.qianfan.QianFanChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClient;

//@Configuration
public class ChatConfig {

    @Autowired
    private QianFanChatModel qianFanChatModel;

    @Bean
    public ChatClient chatClient() {
        return ChatClient
                .builder(qianFanChatModel)
                .build();
    }

    @Bean
    @Primary
    @ConditionalOnProperty(
            prefix = "spring.ai.wenxin.chat",
            name = {"enabled"},
            havingValue = "true",
            matchIfMissing = true
    )
    public WenxinChatModel wenxinChatModel(QianFanConnectionProperties commonProperties,
                                           QianFanChatProperties chatProperties,
                                           RestClient.Builder restClientBuilder, RetryTemplate retryTemplate,
                                           ResponseErrorHandler responseErrorHandler) {
        WenxinApi qianFanApi = this.wenxinApi(chatProperties.getApiKey(), commonProperties.getApiKey(),
                chatProperties.getSecretKey(), commonProperties.getSecretKey(),
                restClientBuilder, responseErrorHandler);
        return new WenxinChatModel(qianFanApi, retryTemplate);
    }

    private WenxinApi wenxinApi(String apiKey, String commonApiKey, String secretKey, String commonSecretKey, RestClient.Builder restClientBuilder, ResponseErrorHandler responseErrorHandler) {
        String resolvedApiKey = StringUtils.hasText(apiKey) ? apiKey : commonApiKey;
        Assert.hasText(resolvedApiKey, "QianFan API key must be set");
        String resolvedSecretKey = StringUtils.hasText(secretKey) ? secretKey : commonSecretKey;
        Assert.hasText(resolvedSecretKey, "QianFan Secret key must be set");
        return new WenxinApi("https://aip.baidubce.com/rpc/2.0/wenxin", resolvedApiKey,
                resolvedSecretKey, restClientBuilder, responseErrorHandler);
    }

}
